package handlers

import (
	"github.com/gin-gonic/gin"
	"pet-manage-sys/models"
	"pet-manage-sys/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": pkg.Md5Str(password),
	})
	return

}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	img := c.PostForm("img")
	content := c.PostForm("content")
	if name == "" || img == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	pet := models.Pet{
		Name:    name,
		Img:     img,
		Content: content,
	}
	err := models.DB.Create(&pet).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size

	var count int64
	models.DB.Model(models.Pet{}).Count(&count)

	var pet []models.Pet
	models.DB.Offset(offset).Limit(size).Find(&pet)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"count": count,
		"pet":   pet,
	})
	return

}
